package com.mashibing.jvm.c3_jmm;

/**
 * 指令重排序，或乱序 校验
 * 可以通过volatile禁止指令重排
 */
public class T04_Disorder {
    private static int a=0,b=0;
    private static int x=0,y=0;

    public static void main(String[] args) throws InterruptedException {
        long count = 0;
        while (true){
            a=0;b=0;
            x=0;y=0;
            count++;
            Thread one = new Thread(()->{
                //由于线程one先启动，下面这句话让它等一等线程two. 读着可根据自己电脑的实际性能适当调整等待时间.
                //shortWait(10000);
                a = 1;
                x = b;
            },"one");
            Thread two =new Thread(()->{
                b = 1;
                y = a;
            },"two");
            one.start(); two.start();
            one.join();two.join();
            String msg = "第 "+ count + " 次，x= "+x+", y="+y;
            if(x == 0 && y == 0){
                System.out.println(msg);
                break;
            }
        }
    }

    public static void shortWait(long interval){
        long start = System.nanoTime();
        long end = 0;
        do {
            end = System.nanoTime();
        }while (start+interval>=end);
    }

}
